/**
 * Created by zn on 17-4-1.
 */
import regular from '../lib/regular'
import captcha from '../model/captcha'
import user from '../model/user'
const captchaModel = new captcha()
const userModel = new user()

module.exports = {
    send: async function(req, res){
        if(!regular.checkEmail(req.body.email) || !regular.checkCaptchaType(req.body.type)){
            console.log(req.body, req.body.type)
            return res.status(200).json({code: 401})
        }
        try {
            let ttl = await captchaModel.getCaptchaTTL(req.body.email, req.body.type)
            if(ttl > 440){
                return res.status(200).json({code: 405})
            }
            let u = await userModel.getUserByEmail(req.body.email)
            if (req.body.type == 1 && u.length > 0) {
                return res.status(200).json({code: 403})
            }else if (req.body.type == 2 && u.length == 0){
                return res.status(200).json({code: 404})
            }
            let randomNumber = captchaModel.createCaptcha()

            captchaModel.sendEmail(req.body.email, randomNumber).then(() => {
                global.redis.set('captcha-' + req.body.email + '-' + req.body.type, randomNumber)
                global.redis.expire('captcha-' + req.body.email + '-' + req.body.type, 600)
                return res.status(200).json({code: 200})
            }).catch(() => {
                return res.status(200).json({code: 406})
            })
        } catch (err) {
            console.log(err)
            return res.status(200).json({code: 402})
        }

    }
}
